<?php

namespace App\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Core\AppKey;

/**
 * 去除空格
 * @author lihaiping
 */
class TrimString implements MiddlewareInterface
{
    /**
     * {@inheritDoc}
     * @see \Psr\Http\Server\MiddlewareInterface::process()
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $param = $this->_transform(R()->all());
        $data = [];
        foreach ($param as $key => $value){
            $data[$key] = $value;
        }

        setContext(AppKey::CONTEXT_HTTP_REQUEST_DATA, $data);
        return $handler->handle($request);
    }
    
    /**
     * 清楚空格
     * @param array $pram
     * @return array
     */
    private function _transform($pram)
    {
        foreach ($pram as $key => $item){
            $isJson = false;
            if( ! is_array($item)){
                $item = trim($item);
                
                if((bool)$item){
                    $_json = $item;
                    try {
                        $_json = json_decode($item, true);
                        if(is_array($_json)){
                            $isJson = true;
                            $item = $_json;
                        }
                    } catch (\Exception $e) {
                        
                    }
                }
            }
            
            if(is_array($item)){
                $item = $this->_transform($item);
            }else{
                $item = trim(urldecode($item));
            }
            
            if($isJson){
                $item = json_encode($item);
            }
            $pram[$key] = $item;
        }
        
        return $pram;
    }
}
